﻿using BBCore.Application.Admins;
using BootstrapBlazor.Components;
using System.ComponentModel.DataAnnotations;

namespace BBCore.Server.Custom_Validators
{
    /// <summary>
    /// 用户名自定义验证,用户名不能重复
    /// </summary>
    public class UserNameValidator : IValidator
    {
        public string? ErrorMessage { get; set; }

        private IAdminService UserService { get; }
        public UserNameValidator(IAdminService userService) => UserService = userService;
        public void Validate(object? propertyValue, ValidationContext context, List<ValidationResult> results)
        {
            //异步竟然不起作用?
            var users = UserService.user_Login(propertyValue?.ToString());
            if (users != null)
            {
                if (!string.IsNullOrEmpty(users.UserName))
                {
                    ErrorMessage = $"{context.DisplayName}已存在";
                }
            }
            else
            {
                ErrorMessage = null;
            }
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                results.Add(new ValidationResult(ErrorMessage, new string[] { context.MemberName! }));
            }
        }
    }
}
